package top.huxy.boot.controller.publicly;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.huxy.boot.annotation.RequestRemake;
import top.huxy.boot.config.Constant;
import top.huxy.boot.model.dto.RegisterUserByEmailForm;
import top.huxy.boot.model.dto.UserLoginForm;
import top.huxy.boot.model.vo.user.VO_User;
import top.huxy.boot.service.UserService;
import top.huxy.boot.util.StringUtils;
import top.huxy.boot.util.obj.Result;

/**
 * @author HuXY
 * @Date 2021年12月30日14:28:35
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestRemake("QQ登录")
    @PostMapping("/qqLogin")
    public Result qqLogin(@RequestParam("openId") String openId, @RequestParam("accessToken") String accessToken) {
        VO_User user = userService.qqLogin(openId, accessToken);
        if (user == null) {
            return Result.clientError("登录失败");
        } else {
            return Result.success(user);
        }
    }

    @RequestRemake("发送邮件验证码")
    @PostMapping("/requestEmailYzm")
    public Result requestEmailYzm(
            @RequestParam("email") String email,
            @RequestParam("yzm") String yzm
    ) {
        userService.requestEmailYzm(email, yzm);
        return Result.success("验证码已发送");
    }

    @RequestRemake(value = "邮箱注册用户", saveParams = false)
    @PostMapping("/registerUserByEmail")
    public Result registerUserByEmail(
            RegisterUserByEmailForm form
    ) {
        userService.registerUserByEmail(form);
        return Result.success("注册成功");
    }

    @RequestRemake(value = "用户登录", saveParams = false)
    @PostMapping("/userLogin")
    public Result userLogin(
            UserLoginForm form
    ) {
        VO_User user = userService.userLogin(form);
        if (user == null) {
            return Result.clientError("登录失败");
        } else {
            return Result.success(user);
        }
    }

    @RequestRemake(value = "用户自动登录")
    @GetMapping("/autoLogin")
    public Result autoLogin(@CookieValue(value = Constant.USER_TOKEN_NAME, required = false, defaultValue = "") String userToken) {
        if (StringUtils.isEmpty(userToken)) {
            return Result.clientError("自动登录失败");
        }
        VO_User user = userService.getVOUserByToken(userToken);
        if (user == null) {
            return Result.clientError("自动登录失败");
        } else {
            return Result.success(user);
        }
    }

    @RequestRemake(value = "用户登出")
    @PostMapping("/logOut")
    public Result logOut(@CookieValue(value = Constant.USER_TOKEN_NAME, required = false, defaultValue = "") String userToken) {
        if (StringUtils.isEmpty(userToken)) {
            return Result.clientError("登出失败");
        }
        userService.logOut(userToken);
        return Result.success("登出成功");
    }
}
